package org.jeecg.modules.third.jg.jss.report.cfcshippingnoteinfo.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.annotation.CurDataSource;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.LngLonUtil;
import org.jeecg.config.DataSourceNames;
import org.jeecg.modules.third.jg.jss.report.cfccarrierinfo.entity.CfcCarrierinfo;
import org.jeecg.modules.third.jg.jss.report.cfccarrierinfo.service.CfcCarrierinfoService;
import org.jeecg.modules.third.jg.jss.report.cfccontractinfo.entity.CfcContractinfo;
import org.jeecg.modules.third.jg.jss.report.cfccontractinfo.service.CfcContractinfoService;
import org.jeecg.modules.third.jg.jss.report.cfcdriverinfo.entity.CfcDriverinfo;
import org.jeecg.modules.third.jg.jss.report.cfcdriverinfo.service.CfcDriverinfoService;
import org.jeecg.modules.third.jg.jss.report.cfcgoodsofvehicle.entity.CfcGoodsofvehicle;
import org.jeecg.modules.third.jg.jss.report.cfcgoodsofvehicle.service.CfcGoodsofvehicleService;
import org.jeecg.modules.third.jg.jss.report.cfcjoborderinfo.entity.CfcJoborderinfo;
import org.jeecg.modules.third.jg.jss.report.cfcjoborderinfo.service.CfcJoborderinfoService;
import org.jeecg.modules.third.jg.jss.report.cfcshippingnoteinfo.entity.CfcShippingnoteinfo;
import org.jeecg.modules.third.jg.jss.report.cfcshippingnoteinfo.mapper.CfcShippingnoteinfoMapper;
import org.jeecg.modules.third.jg.jss.report.cfcvehicleinfo.entity.CfcVehicleinfo;
import org.jeecg.modules.third.jg.jss.report.cfcvehicleinfo.service.CfcVehicleinfoService;
import org.jeecg.modules.third.openapi.WaybillRouteService;
import org.jeecg.modules.wlhy.company.entity.HyCompany;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerAddressReceive;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerAddressSend;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerCompany;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerAddressReceiveService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerAddressSendService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.order.entity.HyOrder;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.entity.WaybillRouteVO;
import org.jeecg.modules.wlhy.utils.CodeUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 运单信息
 * @Description: CFC_SHIPPINGNOTEINFO
 * @Author: jeecg-boot
 * @Date:   2021-11-25
 * @Version: V1.0
 */
@Service
@Slf4j
public class CfcShippingnoteinfoService {

    @Resource
    private CfcShippingnoteinfoMapper cfcShippingnoteinfoMapper;

    ////合同信息表
    @Resource
    private CfcContractinfoService cfcContractinfoService;
   //车载货物信息表，
    @Resource
    private CfcGoodsofvehicleService cfcGoodsofvehicleService;

    //派车单信息表，
    @Resource
    private CfcJoborderinfoService cfcJoborderinfoService;

    //承运人表
    @Resource
    private CfcCarrierinfoService cfcCarrierinfoService;

    //司机表
    @Resource
    private CfcDriverinfoService cfcDriverinfoService;

    //车辆表
    @Resource
    private CfcVehicleinfoService cfcVehicleinfoService;

    @Autowired
    private WaybillRouteService waybillRouteService;

    public String getEnterpriseCode() {
        return enterpriseCode;
    }

    public void setEnterpriseCode(String enterpriseCode) {
        this.enterpriseCode = enterpriseCode;
    }

    private String enterpriseCode;

    @Transactional
    @CurDataSource(name = DataSourceNames.SECOND)
    public  boolean inserShippingNoteInfo(HyShippingNote hyShippingNote, HyCompany company,  HyOrder hyOrder, HyDriver hyDriver, HyVehicle hyVehicle){

        CfcShippingnoteinfo cfcShippingnoteinfo = cfcShippingnoteinfoMapper.selectShippingNoteInfo( hyShippingNote.getShippingNoteNumber() );
        if(cfcShippingnoteinfo != null){
            return false;
        }

        if(company == null){
            log.info("CfcShippingnoteinfoService  inserShippingNoteInfo company:{}", hyShippingNote);
            return false;
        }


        if(hyOrder == null){
            log.info("CfcShippingnoteinfoService  inserShippingNoteInfo hyOrder:{}", hyShippingNote);
            return false;
        }

        if(hyDriver == null){
            log.info("CfcShippingnoteinfoService  inserShippingNoteInfo hyDriver:{}", hyShippingNote);
            return false;
        }

        //派车单表
        CfcJoborderinfo cfcJoborderinfo = saveCfcJoborderinfo(hyShippingNote, hyOrder, hyDriver, hyVehicle);
        saveGoodsofvehicle(hyShippingNote, hyOrder, cfcJoborderinfo);

        //如果没有合同需要记录
        if (StrUtil.isNotEmpty(hyShippingNote.getContractNum())) {
            savaContractInfo(hyShippingNote, company, hyDriver);
        } else {
            log.warn("当前运单没有合同编码 {}", hyShippingNote.getShippingNoteNumber());
        }

        //运单信息
        cfcShippingnoteinfo = ShippingNoteTOCfcShippingNoteInfo(hyShippingNote, hyDriver);
        Integer res = cfcShippingnoteinfoMapper.inserShippingNoteInfo(cfcShippingnoteinfo);
        return res > 0 ? true :false;
    }

    /**
     * 派车单信息
     * @param hyShippingNote
     * @return
     */
    private CfcJoborderinfo saveCfcJoborderinfo(HyShippingNote hyShippingNote, HyOrder hyOrder, HyDriver hyDriver, HyVehicle hyVehicle) {

        CfcJoborderinfo cfcJoborderinfo  =  cfcJoborderinfoService.getJoborderinfoByShinpNum(hyShippingNote.getShippingNoteNumber());
        if(cfcJoborderinfo != null){
            return cfcJoborderinfo;
        }

        cfcJoborderinfo  = ShippingNoteTOCfcJoborderinfo (hyShippingNote, hyOrder, hyDriver, hyVehicle);
        if(cfcJoborderinfo != null){
            cfcJoborderinfoService.insertGoodsofvehicle(cfcJoborderinfo);
        }
        return cfcJoborderinfo;
    }

    /**
     * 车载货物信息
     * @param hyShippingNote
     * @param hyOrder
     * @param cfcJoborderinfo
     */
    private void saveGoodsofvehicle(HyShippingNote hyShippingNote, HyOrder hyOrder, CfcJoborderinfo cfcJoborderinfo) {
        CfcGoodsofvehicle cfcGoodsofvehicle =  cfcGoodsofvehicleService.selectGoodsofvehicleByJobordernumber(cfcJoborderinfo.getJobordernumber());
        if(cfcGoodsofvehicle == null){
            cfcGoodsofvehicle =  new CfcGoodsofvehicle();

            //HyConfig systemConfig = HyConfigUtils.getConfig();
            cfcGoodsofvehicle.setPlatformcode(this.getEnterpriseCode());

            cfcGoodsofvehicle.setGoodsid(hyShippingNote.getOrderId());
            cfcGoodsofvehicle.setJobordernumber(cfcJoborderinfo.getJobordernumber());
            cfcGoodsofvehicle.setGoodsclassificationcode(hyOrder.getCargoTypeClassificationCode());
            cfcGoodsofvehicle.setDescriptionofgoods(hyOrder.getDescriptionOfGoods());
            cfcGoodsofvehicle.setGoodsitemgrossweight(hyShippingNote.getGoodsWeightLoading());
            cfcGoodsofvehicle.setMeasurementunitcode("TNE");
            cfcGoodsofvehicle.setTotalnumberofpackages(1);
            cfcGoodsofvehicle.setConfirmgoodsweight(hyShippingNote.getGoodsWeightUnloading());
            cfcGoodsofvehicle.setConfirmpackages(1);
            cfcGoodsofvehicle.setSigntypecode("001");
            cfcGoodsofvehicle.setConfirmtime(hyShippingNote.getStatusDtSign());
            BigDecimal costPayShipping = hyShippingNote.getDriverFee() ;


            cfcGoodsofvehicle.setCarriage(costPayShipping);
            cfcGoodsofvehicle.setSerialnumber("0000");
            cfcGoodsofvehicleService.insertGoodsofvehicle(cfcGoodsofvehicle);
        }
    }

    public CfcGoodsofvehicle getGoodsOfVehicleInfo(HyShippingNote hyShippingNote, HyOrder hyOrder) {

        CfcGoodsofvehicle cfcGoodsofvehicle =  new CfcGoodsofvehicle();
        cfcGoodsofvehicle.setPlatformcode(this.getEnterpriseCode());
        cfcGoodsofvehicle.setGoodsid(hyShippingNote.getOrderId());
        cfcGoodsofvehicle.setJobordernumber(hyShippingNote.getShippingNoteNumber());
        cfcGoodsofvehicle.setGoodsclassificationcode(hyOrder.getCargoTypeClassificationCode());
        cfcGoodsofvehicle.setDescriptionofgoods(hyOrder.getDescriptionOfGoods());
        cfcGoodsofvehicle.setGoodsitemgrossweight(hyShippingNote.getGoodsWeightLoading());
        cfcGoodsofvehicle.setMeasurementunitcode("TNE");
        cfcGoodsofvehicle.setTotalnumberofpackages(1);
        cfcGoodsofvehicle.setConfirmgoodsweight(hyShippingNote.getGoodsWeightUnloading());
        cfcGoodsofvehicle.setConfirmpackages(1);
        cfcGoodsofvehicle.setSigntypecode("001");
        cfcGoodsofvehicle.setConfirmtime(hyShippingNote.getStatusDtSign());
        BigDecimal costPayShipping = hyShippingNote.getDriverFee() ;

        cfcGoodsofvehicle.setCarriage(costPayShipping);
        cfcGoodsofvehicle.setSerialnumber("0000");

        return cfcGoodsofvehicle;
    }

    public CfcContractinfo getContractInfo(HyShippingNote hyShippingNote, HyCompany company, HyDriver hyDriver) {
        //合同信息表
        CfcContractinfo cfcContractinfo = new CfcContractinfo();
        cfcContractinfo.setContractnumber(StrUtil.isNotEmpty(hyShippingNote.getContractNum()) ?
                hyShippingNote.getContractNum() : "HT" + hyShippingNote.getShippingNoteNumber());
        cfcContractinfo.setContracttype("2");
        cfcContractinfo.setFirstparty(company.getCompanyName());
        cfcContractinfo.setSecondparty(hyDriver.getDriverName());
        BigDecimal costPayShipping = hyShippingNote.getDriverFee() ;

        cfcContractinfo.setContractamount(costPayShipping);
        cfcContractinfo.setContractphotoaccessaddress(
                cfcContractinfoService.getContractAdd(StrUtil.isNotEmpty(hyShippingNote.getShippingContract()) ?
                        hyShippingNote.getShippingContract() : "HT" + hyShippingNote.getShippingNoteNumber() + ".pdf")
        );
        cfcContractinfo.setContractdatetime(hyShippingNote.getCreateTime());

        return cfcContractinfo;
    }


    public CfcContractinfo getShipperContractInfo(HyShippingNote hyShippingNote, HyCustomer hyCustomer, HyCompany company, HyCustomerCompany customerCompany, HyDriver hyDriver) {
        //托运合同信息表
        CfcContractinfo contractinfo = new CfcContractinfo();
        contractinfo.setContractnumber(customerCompany.getContractNumber());
        contractinfo.setContracttype("1");
        contractinfo.setFirstparty(hyCustomer.getCustomerName());
        contractinfo.setSecondparty(company.getCompanyName());
        contractinfo.setContractamount(hyShippingNote.getDriverFee());
        contractinfo.setContractphotoaccessaddress(
                cfcContractinfoService.getContractAdd(customerCompany.getImgContract())
        );
        contractinfo.setContractdatetime(customerCompany.getCreateTime());
        return contractinfo;
    }


    /**
     * 保存承运合同
     * @param hyShippingNote
     * @param company
     * @param hyDriver
     */
    private void savaContractInfo(HyShippingNote hyShippingNote, HyCompany company, HyDriver hyDriver) {
        CfcContractinfo cfcContractinfo =  cfcContractinfoService.getContractinfoByNumber(hyShippingNote.getContractNum());
        if(cfcContractinfo == null){
            //合同信息表
            cfcContractinfo = new CfcContractinfo();

            //HyConfig systemConfig = HyConfigUtils.getConfig();
            cfcContractinfo.setPlatformcode(this.getEnterpriseCode());

            cfcContractinfo.setContractnumber(hyShippingNote.getContractNum());
            cfcContractinfo.setContracttype("2");
            cfcContractinfo.setFirstparty(company.getCompanyName());
            cfcContractinfo.setSecondparty(hyDriver.getDriverName());
            BigDecimal costPayShipping = hyShippingNote.getDriverFee() ;

            cfcContractinfo.setContractamount(costPayShipping);
            cfcContractinfo.setContractphotoaccessaddress(
                    cfcContractinfoService.getContractAdd(hyShippingNote.getShippingContract())
            );
            cfcContractinfo.setContractdatetime(hyShippingNote.getCreateTime());

            cfcContractinfoService.insertContractinfo(cfcContractinfo);
        }
    }

    public CfcJoborderinfo ShippingNoteTOCfcJoborderinfo(HyShippingNote hyShippingNote, HyOrder hyOrder,HyDriver hyDriver, HyVehicle hyVehicle) {
        if(hyShippingNote == null ){
            return null;
        }
        CfcJoborderinfo  cfcJoborderinfo = new CfcJoborderinfo();

        cfcJoborderinfo.setPlatformcode(this.getEnterpriseCode());

        cfcJoborderinfo.setJobordernumber(hyShippingNote.getShippingNoteNumber());
        cfcJoborderinfo.setShippingnotenumber(hyShippingNote.getShippingNoteNumber());

        CfcDriverinfo cfcDriverinfo = this.cfcDriverinfoService.getDriverinfoByIdcard(hyDriver.getIdcard());
        if (null == cfcDriverinfo) {
            throw new JeecgBootException(hyDriver.getDriverName() + "上报数据中驾驶员信息不存在");
        }
        CfcVehicleinfo cfcVehicleinfo = this.cfcVehicleinfoService.getVehicleinfoByNumber(hyVehicle.getVehicleNumber());
        if (null == cfcVehicleinfo) {
            throw new JeecgBootException(hyVehicle.getVehicleNumber() + "上报数据中车辆信息不存在");
        }

        cfcJoborderinfo.setDriverid(cfcDriverinfo.getDriverid());
        cfcJoborderinfo.setVehicleid(cfcVehicleinfo.getVehicleid());
        cfcJoborderinfo.setSinglegenerationtime(hyShippingNote.getStatusDtReceive());
        cfcJoborderinfo.setActualdeparturetime(hyShippingNote.getStatusDtLoading());
        cfcJoborderinfo.setGoodsreceiptdatetime(hyShippingNote.getStatusDtUnloading());

        cfcJoborderinfo.setActualmileage(new BigDecimal(hyShippingNote.getTransportationDistance()).setScale(3, BigDecimal.ROUND_HALF_UP));
        log.info("运单 {}, 公里数{}", hyShippingNote.getShippingNoteNumber(), cfcJoborderinfo.getActualmileage());

        return cfcJoborderinfo;
    }


    @CurDataSource(name = DataSourceNames.SECOND)
    public CfcJoborderinfo ShippingNoteTOCfcJoborderinfoV2(HyShippingNote hyShippingNote, HyOrder hyOrder,
                                                           HyDriver hyDriver, HyVehicle hyVehicle, String compatibleUpload) {

        CfcJoborderinfo  cfcJoborderinfo = new CfcJoborderinfo();
        cfcJoborderinfo.setPlatformcode(this.getEnterpriseCode());
        cfcJoborderinfo.setJobordernumber(hyShippingNote.getShippingNoteNumber());
        cfcJoborderinfo.setShippingnotenumber(hyShippingNote.getShippingNoteNumber());

        if ("1".equals(compatibleUpload)) {
            CfcDriverinfo cfcDriverinfo = this.cfcDriverinfoService.getDriverinfoByIdcard(hyDriver.getIdcard());
            if (null == cfcDriverinfo) {
                cfcJoborderinfo.setDriverid(hyDriver.getId());
            } else {
                cfcJoborderinfo.setDriverid(cfcDriverinfo.getDriverid());
            }

            CfcVehicleinfo cfcVehicleinfo = this.cfcVehicleinfoService.getVehicleinfoByNumber(hyVehicle.getVehicleNumber());
            if (null == cfcVehicleinfo) {
                cfcJoborderinfo.setVehicleid(hyVehicle.getId());
            } else {
                cfcJoborderinfo.setVehicleid(cfcVehicleinfo.getVehicleid());
            }
        } else {
            cfcJoborderinfo.setDriverid(hyDriver.getId());
            cfcJoborderinfo.setVehicleid(hyVehicle.getId());
        }

        cfcJoborderinfo.setSinglegenerationtime(hyShippingNote.getStatusDtReceive());
        cfcJoborderinfo.setActualdeparturetime(hyShippingNote.getStatusDtLoading());
        cfcJoborderinfo.setGoodsreceiptdatetime(hyShippingNote.getStatusDtUnloading());

        cfcJoborderinfo.setActualmileage(new BigDecimal(hyShippingNote.getTransportationDistance()).setScale(3, BigDecimal.ROUND_HALF_UP));
        //log.info("运单 {}, 公里数{}", hyShippingNote.getShippingNoteNumber(), cfcJoborderinfo.getActualmileage());

        return cfcJoborderinfo;
    }

    public CfcShippingnoteinfo ShippingNoteTOCfcShippingNoteInfo(HyShippingNote hyShippingNote, HyDriver hyDriver) {
        if(hyShippingNote == null){
            return null;
        }
        CfcShippingnoteinfo cfcShippingnoteinfo = new CfcShippingnoteinfo();

        //HyConfig systemConfig = HyConfigUtils.getConfig();
        cfcShippingnoteinfo.setPlatformcode(this.getEnterpriseCode());

        cfcShippingnoteinfo.setShippingnotenumber(hyShippingNote.getShippingNoteNumber());

        cfcShippingnoteinfo.setConsignmentdatetime(hyShippingNote.getStatusDtReceive());
        cfcShippingnoteinfo.setBusinesstypecode("1002996");
        cfcShippingnoteinfo.setStatisticstype("2");
        cfcShippingnoteinfo.setSourcegoodsid(hyShippingNote.getOrderId());
        //承运人id，用承运人表里的id不用driverId
        CfcCarrierinfo carrierinfo = this.cfcCarrierinfoService.getCarrierinfoByIdcard(hyDriver.getIdcard());
        if (null == carrierinfo) {
            throw new JeecgBootException("上报数据中承认人信息不存在");
        }
        cfcShippingnoteinfo.setCarrierid(carrierinfo.getCarrierid());
        cfcShippingnoteinfo.setShippingnotestatuscode(hyShippingNote.getShippingStatus());
        cfcShippingnoteinfo.setContractnumber(hyShippingNote.getContractNum());
        cfcShippingnoteinfo.setShippingnotestatuscode("72");
        cfcShippingnoteinfo.setStatuschangedatetime(hyShippingNote.getStatusDtSign());
        cfcShippingnoteinfo.setDespatchactualdatetime(hyShippingNote.getStatusDtReceive());
        cfcShippingnoteinfo.setGoodsreceiptdatetime(hyShippingNote.getStatusDtUnloading());
        cfcShippingnoteinfo.setShippingnoteadddatetime(hyShippingNote.getCreateTime());
        cfcShippingnoteinfo.setShippingnoteaddtype("1");
        cfcShippingnoteinfo.setBusinesstypename("网络货运");
        cfcShippingnoteinfo.setVehicleamount("1");
        cfcShippingnoteinfo.setTransporttypecode("1");

        return cfcShippingnoteinfo;
    }


    public CfcShippingnoteinfo ShippingNoteTOCfcShippingNoteInfoV2(HyShippingNote hyShippingNote, HyDriver hyDriver) {

        CfcShippingnoteinfo cfcShippingnoteinfo = new CfcShippingnoteinfo();
        cfcShippingnoteinfo.setPlatformcode(this.getEnterpriseCode());
        cfcShippingnoteinfo.setShippingnotenumber(hyShippingNote.getShippingNoteNumber());
        cfcShippingnoteinfo.setConsignmentdatetime(hyShippingNote.getStatusDtReceive());
        cfcShippingnoteinfo.setBusinesstypecode("1002996");
        cfcShippingnoteinfo.setStatisticstype("2");
        cfcShippingnoteinfo.setSourcegoodsid(hyShippingNote.getOrderId());
        cfcShippingnoteinfo.setCarrierid(hyDriver.getId());
        cfcShippingnoteinfo.setShippingnotestatuscode(hyShippingNote.getShippingStatus());
        cfcShippingnoteinfo.setContractnumber(StrUtil.isNotEmpty(hyShippingNote.getContractNum()) ?
                hyShippingNote.getContractNum() : "HT" + hyShippingNote.getShippingNoteNumber());
        cfcShippingnoteinfo.setShippingnotestatuscode("72");
        cfcShippingnoteinfo.setStatuschangedatetime(hyShippingNote.getStatusDtSign());
        cfcShippingnoteinfo.setDespatchactualdatetime(hyShippingNote.getStatusDtReceive());
        cfcShippingnoteinfo.setGoodsreceiptdatetime(hyShippingNote.getStatusDtUnloading());
        cfcShippingnoteinfo.setShippingnoteadddatetime(hyShippingNote.getCreateTime());
        cfcShippingnoteinfo.setShippingnoteaddtype("1");
        cfcShippingnoteinfo.setBusinesstypename("网络货运");
        cfcShippingnoteinfo.setVehicleamount("1");
        cfcShippingnoteinfo.setTransporttypecode("1");

        return cfcShippingnoteinfo;
    }


    public CfcShippingnoteinfo selectShippingNoteInfo(String shippingnotenumber) {
        return cfcShippingnoteinfoMapper.selectShippingNoteInfo( shippingnotenumber );
    }


    public Integer deletShippingNoteInfo(String shippingnotenumber) {
        return cfcShippingnoteinfoMapper.deletShippingNoteInfo( shippingnotenumber );
    }
}
